//
//  ITWebViewController.m
//  InTubePro
//
//  Created by seven on 2020/2/6.
//  Copyright © 2020 seven. All rights reserved.
//

#import "ITWebViewController.h"

#import "ITWebViewController(js).h"

static void *KINWebBrowserContext = &KINWebBrowserContext;

@interface ITWebViewController ()<WKNavigationDelegate, WKUIDelegate>{
    
    BOOL _navBarHide;
    
    NSString *_navTitle;
    
    BOOL _isLoading;
    
    UIButton *_reloadBtn;
    
    CFAbsoluteTime _beginTime;
    CFAbsoluteTime _resignTime;
    long _backgroundTime;
}

IT_PROPERTY_STRONG NSDictionary *urlParames;

@end

@implementation ITWebViewController


+ (instancetype)openUrl:(NSString *)url{
    
    NSDictionary *urlParames = [NSDictionary coverFromUrlParamsString:url];
    if (AppUtils.DICT_WORK_MODE) {
        if ([url rangeOfString:@"?"].location == NSNotFound) {
            url = [url stringByAppendingFormat:@"?_jr=1"];
        }
        url = [url stringByAppendingString:@"&_jr=1"];
    }
    
    int istab = [urlParames intValueForKey:@"istab" default:0];
    if (istab != 0) {
        [UIApplication.sharedApplication openURL:[NSURL URLWithString:url] options:nil completionHandler:nil];
        return nil;
    }
    
    ITWebViewController *web = [[self alloc] init];
    web.urlParames = urlParames;
    web.URLString = url;
    [AppUtils pushController:web];
    return web;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.trackName = @"web";
    if (_urlParames == nil) {
        self.urlParames = [NSDictionary coverFromUrlParamsString:_URLString];
    }
    _wkWebView = [WKWebView initWithFrame:self.contentFrame];
    _wkWebView.navigationDelegate = self;
    _wkWebView.UIDelegate = self;
    _wkWebView.scrollView.alwaysBounceVertical = YES;
    [self.view insertSubview:_wkWebView belowSubview:self.topView];
    if (@available(iOS 11.0, *)) {
        _wkWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    _wkWebView.backgroundColor = self.view.backgroundColor;
    _wkWebView.scrollView.backgroundColor = self.view.backgroundColor;
    
    [_wkWebView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:KINWebBrowserContext];
    
    _progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    _progressView.progressTintColor = COLOR_Link;
    [_progressView setTrackTintColor:[UIColor colorWithWhite:1.0f alpha:0.0f]];
    [_progressView setFrame:CGRectMake(0, _wkWebView.top, self.view.frame.size.width, self.progressView.frame.size.height)];
    _progressView.alpha = 0;
    [self.view addSubview:_progressView];
    
    [self loadURLString:_URLString];
    
    [self setupJSFunctions];
    /*
    [_wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
       NSLog(@"userAgent :%@", result);
    }];
    //*/
    
    if (_urlParames) {
        id fullScreen = _urlParames[@"screen"];
        if (fullScreen) {
            int isFullScreen = [fullScreen intValue];
            _navBarHide =  (isFullScreen == 1);
        }
        _navTitle = _urlParames[@"title"];
        if (_navTitle) {
            self.titleLbl.text = _navTitle;
        }
    }
    
    if (_navBarHide) {
        [self setHideTopView:YES];
        self.wkWebView.frame = UIScreen.mainScreen.bounds;
        _progressView.top = _wkWebView.top;
    }
    
    _beginTime = CACurrentMediaTime();
}

#pragma mark - time
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self viewAppear];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self viewDisAppear];
}

- (void)didBecomeActive{
    [super didBecomeActive];
    [self viewAppear];
}

- (void)willResignActive{
    [super willResignActive];
    [self viewDisAppear];
}   

- (void)viewAppear{
    if (_resignTime>0) {
        _backgroundTime += CACurrentMediaTime()-_resignTime;
    }
    [self AppEventMessage:2];
}

- (void)viewDisAppear{
    _resignTime = CACurrentMediaTime();
    [self AppEventMessage:1];
}



/*
- (void)willDealloc{
    _duration = CACurrentMediaTime() - _beginTime - _backgroundTime;
    [super willDealloc];
}//*/

#pragma mark - load

- (void)reloadView{
    if (!_isLoading) {
        [self loadURLString:_URLString];
    }
    [self setHideTopView:_navBarHide];
    _reloadBtn.hidden = YES;
}

- (void)loadRequest:(NSURLRequest *)request {
    [self.wkWebView loadRequest:request];
    
    [self performSelector:@selector(showReloadBtn) withObject:nil afterDelay:5];
}

- (void)loadURL:(NSURL *)URL {
    _isLoading = YES;
    _loadError = NO;
    [self loadRequest:[NSURLRequest requestWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10]];
}

- (void)loadURLString:(NSString *)URLString {
    NSURL *URL = [NSURL URLWithString:URLString.stringByTrim];
    [self loadURL:URL];
}

- (void)loadHTMLString:(NSString *)HTMLString {
    [self.wkWebView loadHTMLString:HTMLString baseURL:nil];
}


- (void)onLoadError:(NSError *)error{
    _loadError = YES;
    _isLoading = NO;
    [self.view showInfo:error.localizedDescription ?: LocalTitle(@"network error!")];
    [self showReloadBtn];
}

- (void)showReloadBtn{
    [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(showReloadBtn) object:nil];
    [self setHideTopView:NO];
    if (_reloadBtn == nil) {
        CGRect rect = self.backBtn.frame;
        rect.origin.x = self.view.width-rect.size.width;
        _reloadBtn = [UIButton initWithFrame:rect];
        _reloadBtn.titleLabel.font = defaultFontWithSize(16);
        [_reloadBtn setTitleColor:self.backBtn.tintColor];
        [_reloadBtn setTitleNormal:LocalTitle(@"Reload")];
        [_reloadBtn addTarget:self action:@selector(reloadView)];
        [self.topView addSubview:_reloadBtn];
    }
    _reloadBtn.hidden = NO;
}

- (void)hideReloadBtn{
    [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(showReloadBtn) object:nil];
    if (_navBarHide) {
        [self setHideTopView:YES];
    }
    _reloadBtn.hidden = YES;
}

#pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSURL *url = webView.URL;
    if ([url.absoluteString isEqualToString:@"about:blank"]) {
        NSErrorDomain domain = @"com.daofu.invid.error";
        NSError *error = [NSError errorWithDomain:domain code:0 userInfo:@{NSLocalizedDescriptionKey: LocalTitle(@"The URL can’t be shown")}];
        [self onLoadError:error];
        return;
    }
    if (_navTitle == nil) {
        self.titleLbl.text = webView.title;
    }
    _isLoading = NO;
    [webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        
    }];

    [webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none';" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        
    }];
    
    if (_loadtime <= 0) {
        _loadtime = CACurrentMediaTime() - _beginTime;
    }
    [self hideReloadBtn];
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation
      withError:(NSError *)error {
    [self onLoadError:error];
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation
      withError:(NSError *)error {
    [self onLoadError:error];
}


- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    if(webView == self.wkWebView) {
        
        NSURL *URL = navigationAction.request.URL;
        if(![self externalAppRequiredToOpenURL:URL]) {
            if(!navigationAction.targetFrame) {
                [self loadURL:URL];
                decisionHandler(WKNavigationActionPolicyCancel);
                return;
            }
        }
        else if([[UIApplication sharedApplication] canOpenURL:URL]) {
            [self launchExternalAppWithURL:URL];
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}
#pragma mark - External App Support

- (BOOL)externalAppRequiredToOpenURL:(NSURL *)URL {
    NSSet *validSchemes = [NSSet setWithArray:@[@"http", @"https"]];
    return ![validSchemes containsObject:URL.scheme];
}

- (void)launchExternalAppWithURL:(NSURL *)URL {
    if (_externalAppPermissionAlert == nil) {
        WEAKSELF
        _externalAppPermissionAlert = [UIAlertController alertControllerWithTitle:@"Leave this app?" message:@"This web page is trying to open an outside app. Are you sure you want to open it?" preferredStyle:(UIAlertControllerStyleAlert)];
        [_externalAppPermissionAlert addAction:[UIAlertAction actionWithTitle:@"Open App" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:weak_self.URLToLaunchWithPermission options:nil completionHandler:nil];
            weak_self.URLToLaunchWithPermission = nil;
        }]];
        [_externalAppPermissionAlert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
            weak_self.URLToLaunchWithPermission = nil;
        }]];
    }
    if (_URLToLaunchWithPermission == nil) {
        [[AppUtils findRootController] presentViewController:_externalAppPermissionAlert animated:YES completion:nil];
    }else {
        
    }
    self.URLToLaunchWithPermission = URL;
}
#pragma mark - WKUIDelegate

- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}


#pragma mark - Estimated Progress KVO (WKWebView)

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.wkWebView) {
        [self.progressView setAlpha:1.0f];
        BOOL animated = self.wkWebView.estimatedProgress > self.progressView.progress;
        [self.progressView setProgress:self.wkWebView.estimatedProgress animated:animated];
        
        // Once complete, fade out UIProgressView
        if(self.wkWebView.estimatedProgress >= 1.0f) {
            [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:NO];
            }];
        }
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}


- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}

@end
